package com.demo.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.protocol.RequestContent;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@RefreshScope
public class PreFilter extends ZuulFilter {
    @Value("${mysql.user}")
    private String user;

    @Value("${token}")
    private String token;

    @Override
    public String filterType() {  //过滤器类型
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {   //过滤器执行顺序
        return 0;
    }

    @Override
    public boolean shouldFilter() {  //过滤器是否起作用，true为是

        return true;
    }

    @Override
    public Object run() throws ZuulException {  //过滤器逻辑处理
        System.out.println("user="+user);
        System.out.println("token="+token);
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest httpServletRequest = requestContext.getRequest();
        String token=httpServletRequest.getHeader("token");
        if(token!=null){
            System.out.println("1");
            requestContext.setSendZuulResponse(true);
            httpServletRequest.setAttribute("flag",1);
        }else {
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);
            requestContext.setResponseBody("no authrazation");
            System.out.println("2");
        }
        return null;
    }
}
